/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package AdminGUI;

import LocalDB.Product;
import LocalDB.Store;
import java.awt.Component;
import java.util.*;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.ListModel;
import supermarket.*;

/**
 *
 * @author Panagis
 */
public class AssignProductsPanel extends javax.swing.JPanel {

    /**
     * Creates new form AssignProductsPanel
     */
    
    private SuperMarketParentFrame frame;
    private Store sto;
    private List<Product> avProd;
    private EntityManager loc;
    
//Constructor
    public AssignProductsPanel(SuperMarketParentFrame frame) {
        this.frame = frame;
        this.sto = new Store();
        this.avProd = new ArrayList<>(0);
        this.loc = frame.getLoc();
        initComponents();
        if (!loc.getTransaction().isActive()) {
            loc.getTransaction().begin();
        }
     }

    
    private List<Product> getAvProdList(Store st){
            List<Product> avProdCol = new ArrayList<>(0);
            List<Product> allProdCol = new ArrayList<>(0);
            try {
                Query q = loc.createNativeQuery("SELECT * FROM PRODUCT p WHERE PRODUCT_ID NOT IN "
                        + "(SELECT PRODUCT FROM STORE_PRODUCT WHERE STORE = "
                        +st.getStoreId().toString()+")",Product.class);
                allProdCol = q.getResultList();
                avProdCol.clear();
                for (Product p : allProdCol) {
                    if (!st.getProductCollection().contains(p)) {
                        avProdCol.add(p);
                    }
                }
            return avProdCol;
            } catch (NoResultException e) {
                e.printStackTrace();
                loc.getTransaction().rollback();
                avProdCol.clear();
                return null;
            } catch (Exception e){

                avProdCol.clear();
                return null;
            }
    }
    
    private void repaintAvProd(Store sto){
        avProd = getAvProdList(sto);
        DefaultListModel<Product> model = new DefaultListModel();
        for (Product p : avProd) {
            model.addElement(p);
        }
        AvailableProducts.setModel(model);
    }
    
    private void repaintStProd(Store sto){
        DefaultListModel<Product> model = new DefaultListModel();
        for (Product p : sto.getProductCollection()) {
            model.addElement(p);
        }
        StoreProductsList.setModel(model);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("SuperMarket-local-PU").createEntityManager();
        storeQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT s FROM Store s");
        storeList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : storeQuery.getResultList();
        storeQuery1 = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT s FROM Store s");
        storeList1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : storeQuery1.getResultList();
        productQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT p FROM Product p");
        productList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : productQuery.getResultList();
        GoBack = new javax.swing.JButton();
        StoreSelectComboBox = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        StoreProductsList = new javax.swing.JList();
        RemoveButton = new javax.swing.JButton();
        AddButton = new javax.swing.JButton();
        SaveButton = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        AvailableProducts = new javax.swing.JList();
        CancelButton = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Συσχέτιση Προϊόντων"));
        setName(""); // NOI18N

        GoBack.setText("Επιστροφή");
        GoBack.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                GoBackActionPerformed(evt);
            }
        });

        StoreSelectComboBox.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(
                JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                if (value instanceof Store) {
                    sto = (Store)value;
                    setText(sto.getName());
                } else {
                    setText("Επιλέξτε Κατάστημα...");
                }
                return this;
            }
        });

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, storeList, StoreSelectComboBox);
        bindingGroup.addBinding(jComboBoxBinding);
        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, StoreSelectComboBox, org.jdesktop.beansbinding.ELProperty.create("${selectedItem.name}"), StoreSelectComboBox, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        StoreSelectComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                StoreSelectComboBoxActionPerformed(evt);
            }
        });

        StoreProductsList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        StoreProductsList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        StoreProductsList.setCellRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                Component renderer = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                if (value instanceof Product) {
                    setText(((Product)value).getName());
                }
                return renderer;
            }
        });
        StoreProductsList.setFixedCellHeight(15);
        StoreProductsList.setFixedCellWidth(250);
        StoreProductsList.setFocusCycleRoot(true);

        org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${selectedItem.productCollection}");
        org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings.createJListBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, StoreSelectComboBox, eLProperty, StoreProductsList);
        bindingGroup.addBinding(jListBinding);

        jScrollPane1.setViewportView(StoreProductsList);

        RemoveButton.setText("<-");
        RemoveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RemoveButtonActionPerformed(evt);
            }
        });

        AddButton.setText("->");
        AddButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddButtonActionPerformed(evt);
            }
        });

        SaveButton.setText("Αποθήκευση");
        SaveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveButtonActionPerformed(evt);
            }
        });

        jScrollPane2.setEnabled(false);

        AvailableProducts.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        AvailableProducts.setAutoscrolls(false);
        AvailableProducts.setCellRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                Component renderer = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                if (value instanceof Product) {
                    setText(((Product)value).getName());
                }
                return renderer;
            }
        });
        AvailableProducts.setDoubleBuffered(true);
        AvailableProducts.setFixedCellHeight(15);
        AvailableProducts.setFixedCellWidth(250);
        AvailableProducts.setFocusCycleRoot(true);
        AvailableProducts.setVisibleRowCount(-1);
        jScrollPane2.setViewportView(AvailableProducts);
        AvailableProducts.getAccessibleContext().setAccessibleDescription("");

        CancelButton.setText("Ακύρωση");
        CancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(478, 478, 478)
                        .addComponent(StoreSelectComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(22, 22, 22)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(AddButton, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(RemoveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addComponent(GoBack))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(CancelButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(SaveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(18, 18, 18))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(StoreSelectComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(85, 85, 85)
                        .addComponent(AddButton, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(2, 2, 2)
                        .addComponent(RemoveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(GoBack)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(SaveButton)
                        .addComponent(CancelButton))))
        );

        bindingGroup.bind();
    }// </editor-fold>//GEN-END:initComponents

    private void GoBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GoBackActionPerformed
        Object[] options = {"Ναι","Οχι"};
        Integer choice = JOptionPane.showOptionDialog(null,
        "Όλες οι αλλαγές θα χαθούν. Είστε σίγουρος;",
        "Επαναφορά στο αρχικό μενού.",
        JOptionPane.YES_NO_OPTION,
        JOptionPane.QUESTION_MESSAGE,
        null,
        options,
        options[0]);

        if (choice == JOptionPane.YES_OPTION){
            if (loc.getTransaction().isActive()) {
                try {
                    loc.getTransaction().rollback();
                    frame.pnl = new MainPanel(frame);
                    frame.addPanelInMain();
                } catch (Exception e) {
                        e.printStackTrace();
                    loc.getTransaction().rollback();            
                }
            }
        }
    }//GEN-LAST:event_GoBackActionPerformed

    private void AddButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddButtonActionPerformed
        Integer avLstPos = AvailableProducts.getSelectedIndex();
        if (avLstPos != -1) {
            if (loc.getTransaction().isActive()) {
                    try {
                    List<Product> pr = AvailableProducts.getSelectedValuesList();
                    sto.getProductCollection().addAll(pr);
                    for (Product p : pr) {
                        p.getStoreCollection().add(sto);
                        loc.merge(p);
                    }
                    loc.merge(sto);
                    StoreSelectComboBoxActionPerformed(null);
                    } catch (Exception e) {
                    e.printStackTrace();
                    loc.getTransaction().rollback();
                }
            }
        }
    }//GEN-LAST:event_AddButtonActionPerformed

    private void StoreSelectComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StoreSelectComboBoxActionPerformed
        if (sto.getStoreId() != null) {
            sto = (Store)StoreSelectComboBox.getSelectedItem();
            repaintStProd(sto);
            repaintAvProd(sto);
        }
    }//GEN-LAST:event_StoreSelectComboBoxActionPerformed

    private void SaveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveButtonActionPerformed
        Object[] options = {"Ναι","Οχι"};
        Integer choice = JOptionPane.showOptionDialog(null,
        "Επιβεβαίωση αλλαγών;",
        null,
        JOptionPane.YES_NO_OPTION,
        JOptionPane.QUESTION_MESSAGE,
        null,
        options,
        options[0]);

        if (choice == JOptionPane.YES_OPTION){
            if (loc.getTransaction().isActive()) {
                try {
                    loc.getTransaction().commit();
                    frame.pnl = new MainPanel(frame);
                    frame.addPanelInMain();                    
                } catch (Exception e) {
                        e.printStackTrace();
                    loc.getTransaction().rollback();            
                }
            }
        } 
    }//GEN-LAST:event_SaveButtonActionPerformed

    private void RemoveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RemoveButtonActionPerformed
        Integer avLstPos = StoreProductsList.getSelectedIndex();
        if (avLstPos != -1) {
            if (loc.getTransaction().isActive()) {
                    try {
                    List<Product> pr = StoreProductsList.getSelectedValuesList();
                    sto.getProductCollection().removeAll(pr);
                    for (Product p : pr) {
                        p.getStoreCollection().remove(sto);
                        loc.merge(p);
                    }
                    loc.merge(sto);
                    StoreSelectComboBoxActionPerformed(null);
                    } catch (Exception e) {
                    e.printStackTrace();
                    loc.getTransaction().rollback();
                }
            }
        }
    }//GEN-LAST:event_RemoveButtonActionPerformed

    private void CancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelButtonActionPerformed
        Object[] options = {"Ναι","Οχι"};
        Integer choice = JOptionPane.showOptionDialog(null,
        "Ακύρωση αλλαγών;",
        null,
        JOptionPane.YES_NO_OPTION,
        JOptionPane.QUESTION_MESSAGE,
        null,
        options,
        options[0]);

        if (choice == JOptionPane.YES_OPTION){
            if (loc.getTransaction().isActive()) {
                try {
                    loc.getTransaction().rollback();
                    frame.pnl = new AssignProductsPanel(frame);
                    frame.addPanelInMain();
                } catch (Exception e) {
                        e.printStackTrace();
                    loc.getTransaction().rollback();            
                }
            }
        }
    }//GEN-LAST:event_CancelButtonActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AddButton;
    private javax.swing.JList AvailableProducts;
    private javax.swing.JButton CancelButton;
    private javax.swing.JButton GoBack;
    private javax.swing.JButton RemoveButton;
    private javax.swing.JButton SaveButton;
    private javax.swing.JList StoreProductsList;
    private javax.swing.JComboBox StoreSelectComboBox;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private java.util.List<LocalDB.Product> productList;
    private javax.persistence.Query productQuery;
    private java.util.List<LocalDB.Store> storeList;
    private java.util.List<LocalDB.Store> storeList1;
    private javax.persistence.Query storeQuery;
    private javax.persistence.Query storeQuery1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
